<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          placeholder="模板名称"
          @keyup.enter.native="getData()"
          clearable
          v-model="params['contract_title.eq']"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="合同类型"
          clearable
          :options="enumContractType"
          v-model="params['contract_type_code.eq']"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" @click="editContract()">新增模板</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:content="scope">
        <div class="text-truncate" :title="scope.row.content">{{ scope.row.content }}</div>
      </template>
      <template v-slot:operate="scope">
        <el-button type="text" @click="editContract(scope.row)">
          <i class="fa fa-edit"></i>
        </el-button>
        <el-button
          type="text"
          @click="handleDownload(scope.row)"
          :loading="loadingId === scope.row.contract_template_id"
        >
          <i class="fa fa-download"></i>
        </el-button>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>
    <contract-edit
      :visible.sync="visible"
      :cfcaId="cfcaId"
      :formData="formData"
      @success="getData(params.index)"
    ></contract-edit>
  </div>
</template>

<script>
import { dateFormat } from '@/common/utils/common'
import { enumContractType } from '@/credit/plugins/enumCadmin'
import { getData } from '@/common/api/cfca'
import { mapGetters } from 'vuex'
import ContractEdit from '@/credit/views/cadmin/contract/ContractEdit'
export const base64ToBlob = content => {
  let parts = content.split(';base64,')
  let contentType = parts[0].split(':')[1]
  let raw = window.atob(parts[1])
  let rawLength = raw.length

  let uInt8Array = new Uint8Array(rawLength)

  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uInt8Array], { type: contentType })
}
export const downLoad = (imgbase, fileName) => {
  const aLink = document.createElement('a')
  aLink.download = fileName
  const blob = base64ToBlob(imgbase)
  aLink.href = URL.createObjectURL(blob)
  aLink.click()
}

export const viewFile = (imgbase, _fileName) => {
  const aLink = document.createElement('a')
  aLink.setAttribute('target', '_blank')
  const blob = base64ToBlob(imgbase)
  aLink.href = URL.createObjectURL(blob)
  aLink.click()
}
export default {
  components: {
    ContractEdit,
  },
  data() {
    return {
      enumContractType,
      params: {
        index: 1,
        size: 15,
      },
      order: { create_time: 'desc' },
      tableCount: 0,
      tableName: 'contract_template',
      loading: false,
      tableColumns: [
        {
          attrs: { label: '创建时间', prop: 'create_time', align: 'center', width: 180 },
          process: v => dateFormat(v, 'yyyy-MM-dd hh:mm'),
        },
        { attrs: { label: '模板名称', prop: 'contract_title' } },
        {
          attrs: { label: '合同类型', prop: 'contract_type_code' },
          process: v => enumContractType[v],
        },
        // { attrs: { label: '模板参数', prop: 'key_infos' } },
        {
          attrs: { label: '操作', align: 'center', width: 140 },
          slot: 'operate',
        },
      ],
      tableData: [],
      loadingId: '',
      visible: false,
      cfcaId: '',
      formData: {},
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  created() {
    this.params['service_id.eq'] = this.clientId
    this.getData()
  },
  methods: {
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData('credit', this.tableName, this.params, this.order)
        .then(res => {
          this.tableData = (res && res.data && res.data.data) || []
          this.tableCount = (res && res.data && res.data.totalCount) || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDownload(row) {
      this.loadingId = row.contract_template_id
      getData('contract/template', { templateId: row.template_id })
        .then(res => {
          const data = (res && res.data) || {}
          let fileBase = (data.contractTemplate && data.contractTemplate.data) || ''
          fileBase = `data:application/pdf;base64,${fileBase}`
          downLoad(fileBase, `${row.contract_title}.pdf`)
        })
        .finally(() => {
          this.loadingId = ''
        })
    },
    editContract(row) {
      this.cfcaId = row ? row.template_id : ''
      this.formData = row ? { ...row } : {}
      this.visible = true
    },
  },
}
</script>
<style lang="scss" scoped></style>
